package com.yuantong.xyerp.rest.config.APIJson;

import apijson.Log;
import apijson.column.ColumnUtil;
import apijson.orm.AbstractSQLExecutor;
import apijson.orm.SQLConfig;
import com.alibaba.fastjson.JSONObject;
import com.yuantong.xyerp.XyerpRestApplication;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Map;

/**
 * Created by Jianguo.Yin on 2021-07-02.
 */
public class XyerpSQLExecutor extends AbstractSQLExecutor {
    public static final String TAG = "XyerpSQLExecutor";

    @Override
    public Connection getConnection(SQLConfig config) throws Exception {
        Log.d(TAG, "getConnection  config.getDatasource() = " + config.getDatasource());

        Connection c = connectionMap.get(config.getDatabase());
        if (c == null || c.isClosed()) {
            try {
                /** 从Bean获得连接池, getApplicationContext()这个方法是作者在启动器中自定义的*/
                DataSource ds = XyerpRestApplication.getApplicationContext().getBean(DataSource.class);
                // 另一种方式是 DruidConfig 初始化获取到 Datasource 后给静态变量 DATA_SOURCE 赋值： ds = DruidConfig.DATA_SOURCE.getConnection();
                connectionMap.put(config.getDatabase(), ds == null ? null : ds.getConnection());
            } catch (Exception e) {
                Log.e(TAG, "getConnection   try { "
                        + "DataSource ds = DemoApplication.getApplicationContext().getBean(DataSource.class); .."
                        + "} catch (Exception e) = " + e.getMessage());
            }
        }

        // 必须最后执行 super 方法，因为里面还有事务相关处理。
        // 如果这里是 return c，则会导致 增删改 多个对象时只有第一个会 commit，即只有第一个对象成功插入数据库表
        return super.getConnection(config);
    }



    // 取消注释支持 !key 反选字段 和 字段名映射，需要先依赖插件 https://github.com/APIJSON/apijson-column
    @Override
    protected String getKey(SQLConfig config, ResultSet rs, ResultSetMetaData rsmd, int tablePosition, JSONObject table,
                            int columnIndex, Map<String, JSONObject> childMap) throws Exception {
        return ColumnUtil.compatOutputKey(super.getKey(config, rs, rsmd, tablePosition, table, columnIndex, childMap), config.getTable(), config.getMethod());
    }



}
